<?php
namespace App\Api\Controller;
use App\app\Models\Exchangerate;
use App\Constant\SendMess;
use App\Models\Goldcoins;
use App\Models\Order;
use App\Models\SilverDollarCoin;
use App\Models\SmsLogs;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use ModStart\Admin\Model\Config;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Input\InputPackage;
use ModStart\Core\Input\Response;
use Module\Member\Support\MemberLoginCheck;
use Module\Member\Util\MemberBlogUtil;
use ModStart\Core\Exception\BizException;

class BlogController extends Controller implements MemberLoginCheck
{
    public static $memberLoginCheckIgnores = ['getIntroImg','sendMessage'];

    public function paginate()
    {
        $input = InputPackage::buildFromInput();
        $user_id = $input->getInteger('user_id');
        $name = $input->get('name');
        if(isset($user_id) && $user_id>0 ){
            $user_info = DB::table("member_user")->where("id",$user_id)->first();
            if(!$user_info){
                return Response::generateError("该用户不存在!",[]);
            }
            $blog_id = DB::table("bindwallet")->where("user_id",$user_id)->select("blog_id")->get();
           $arr = [];
           foreach($blog_id as $v){
               $arr[] = $v->blog_id;
           }
            if(!empty($name)){
                $paginateData =   DB::table("blog")->where(['state'=>1])->whereNotIn('id', $arr)->where("title","like",$name)->get();
            }else{
                $paginateData =   DB::table("blog")->where(['state'=>1])->whereNotIn('id', $arr)->get();
            }
        }else{
            if(!empty($name)){
                $paginateData =   DB::table("blog")->where(['state'=>1])->where('id','>',2)->where("title","like",$name)->get();
            }else{
                $paginateData =   DB::table("blog")->where(['state'=>1])->where('id','>',2)->get();
            }

        }
        //获取今日龙币价格
//        $today = Carbon::today();
//        // 查询小于今天的数据
//        $results = SilverDollarCoin::whereDate('date_time', '<=', $today)->orderBy("date_time","desc")->first();
        foreach($paginateData as $k=>&$v){
            $v->summary = 0;
            if($v->id ==1){ //人民币
//                $rate =   Exchangerate::where(['blog_id'=>1,'ex_blog_id'=>2])->first();
                $v->summary = 1;
                continue;
            }elseif ($v->id ==2){  //龙币
//                $v->summary = $results->price;
//                continue;
                $rate =   Exchangerate::where(['blog_id'=>1,'ex_blog_id'=>2])->first();
            }else{ //其他
                $rate =   Exchangerate::where(['blog_id'=>2,'ex_blog_id'=>$v->id])->first();
            }
            if(!empty($rate)){
                $v->summary = $rate->ex_rates;
            }
        }
        if($paginateData){
            return Response::generateSuccessData($paginateData);
        }
        return Response::generateSuccessData([]);
    }


    /***
     * @return array
     * 获取已绑定的钱包
     */
    public function selfPaginate()
    {
        $input = InputPackage::buildFromInput();
        $user_id = $input->getInteger('user_id');
        if(isset($user_id) && $user_id>0 ){
            $user_info = DB::table("member_user")->where("id",$user_id)->first();
            if(!$user_info){
                return Response::generateError("该用户不存在!",[]);
            }
            $blog_id = DB::table("bindwallet")->where("user_id",$user_id)->select("blog_id")->get();
            $arr = [];
            foreach($blog_id as $v){
                $arr[] = $v->blog_id;
            }
            $paginateData =   DB::table("blog")->where(['state'=>1])->whereIn('id', $arr)->get();
        }else{
            $paginateData =   DB::table("blog")->where(['state'=>1])->where('id','>',2)->get();
        }
        //获取今日龙币价格
//        $today = Carbon::today();
        // 查询小于今天的数据
//        $results = SilverDollarCoin::whereDate('date_time', '<=', $today)->orderBy("date_time","desc")->first();
        foreach($paginateData as $k=>&$v){
            $v->summary = 0;
            if($v->id ==1){ //人民币
                $v->summary = 1;
                continue;
            }elseif ($v->id ==2){  //龙币
                $rate =   Exchangerate::where(['blog_id'=>1,'ex_blog_id'=>2])->first();
            }else{ //其他
                $rate =   Exchangerate::where(['blog_id'=>2,'ex_blog_id'=>$v->id])->first();
            }
            if(!empty($rate)){
                $v->summary = $rate->ex_rates;
            }
        }
        if($paginateData){
            return Response::generateSuccessData($paginateData);
        }
        return Response::generateSuccessData([]);
    }





    public function get()
    {
        $input = InputPackage::buildFromInput();
        $id = $input->getInteger('id');
        $user_id = $input->getInteger('user_id');
        $where = ['id'=>$id,'state'=>1];
        $record = ModelUtil::get('blog', $where);
        if (!$record) {
            return Response::jsonError("该帐户不存在");
        }
        if ($record['id'] == 1) { //人民币
            $info = DB::table('bindwallet')
                ->join('member_user', 'member_user.id', '=', 'bindwallet.user_id')
                ->join('blog', 'bindwallet.blog_id', '=', 'blog.id')
                ->select('bindwallet.*', 'blog.title', 'blog.cover', 'blog.summary', 'blog.icon', 'blog.content','blog.theme_color')
                ->where(['bindwallet.user_id' => $user_id])
                ->where('blog.id', '=', 1)
                ->get();
//            $rate =   Exchangerate::where(['blog_id'=>1,'ex_blog_id'=>2])->first();
            $record['summary'] = 1;
//            if($rate){
//                $record['summary'] = $rate->ex_rates;
//            }
            $record['other_list'] = $info;
        } elseif ($record['id'] == 2) { //龙币
            //获取今日龙币价格
//            $today = Carbon::today();
            // 查询小于今天的数据
//            $results = SilverDollarCoin::whereDate('date_time', '<=', $today)->orderBy("date_time","desc")->first();
            $info = DB::table('bindwallet')
                ->join('member_user', 'member_user.id', '=', 'bindwallet.user_id')
                ->join('blog', 'bindwallet.blog_id', '=', 'blog.id')
                ->select('bindwallet.*', 'blog.title', 'blog.cover', 'blog.summary', 'blog.icon', 'blog.content','blog.theme_color')
                ->where(['bindwallet.user_id' => $user_id])
                ->where('blog.id', '=', 1)
                ->get();
            $rate =   Exchangerate::where(['blog_id'=>1,'ex_blog_id'=>2])->first();
            $record['summary'] = $rate->ex_rates;
            $record['other_list'] = $info;
        } else { //其他
        //判断该账号是否已经绑定
            $is_blog =  DB::table('bindwallet')->where(["user_id"=>$user_id,'blog_id'=>$record['id']])->first();
            if(!$is_blog){
               return Response::generateError("您还没有绑定该账户类型",[]);
            }
            $info = DB::table('bindwallet')
                ->join('member_user', 'member_user.id', '=', 'bindwallet.user_id')
                ->join('blog', 'bindwallet.blog_id', '=', 'blog.id')
                ->select('bindwallet.*', 'blog.title', 'blog.cover', 'blog.summary', 'blog.icon', 'blog.content','blog.theme_color')
                ->where(['bindwallet.user_id' => $user_id])
                ->where('blog.id', '=', 2)
                ->get();
            $rate =   Exchangerate::where(['blog_id'=>2,'ex_blog_id'=>$record['id']])->first();
            $record['summary'] = 0;
            if($rate){
                $record['summary'] = $rate->ex_rates;
            }
            $record['other_list'] = $info;
        }
        return Response::generateSuccessData([
            'record' => $record,
        ]);
    }

    /***
     * 龙币兑换其他货币(暂时没有用)
     */
//    public function doExchange()
//    {
//        $input = InputPackage::buildFromInput();
////        $id = $input->getInteger('id'); //当前账户卡片id
//        $user_id = $input->getInteger('user_id');
//        $blog_id = $input->getInteger('blog_id'); //卡片id
//        $start_blog_id = $input->getInteger('start_blog_id'); //龙币id
//        $money = $input->getInteger('numbers'); //数量
//        $data = [];
//        $data['money'] = $money;
//        $data['user_id'] = $user_id;
//        $data['blog_id'] = $blog_id;
//        $data['start_blog_id'] = $start_blog_id;
//        BizException::throwsIfEmpty('兑换数量不能为空', $data['money']);
//        BizException::throwsIfEmpty('用户ID不能为空', $data['user_id']);
//        BizException::throwsIfEmpty('账号id不能为空', $data['blog_id']);
//        BizException::throwsIfEmpty('龙币账号ID不能为空', $data['start_blog_id']);
//        $lit = (new Order())->exchange($data);
//        if ($lit == true) {
//            return Response::jsonSuccess("储蓄成功!");
//        }
//        return Response::jsonError("储蓄失败!");
//    }

    /***
     * 储值人民币
     * 储蓄/转出/兑换
     */
    public function storedValue()
    {
        $input = InputPackage::buildFromInput();
        $money = $input->get('money');
        $number = $input->getInteger('number');
        $user_id = $input->getInteger('user_id');
        $pay_type = $input->getInteger('pay_type');
        $add_type = $input->getInteger('add_type');
        $password = $input->getTrimString('password');
        $e_blog_id = $input->getInteger('e_blog_id'); //进钱方
        $s_blog_id = $input->getInteger('s_blog_id'); //出钱方
        $data = [];
        $data['money'] = $money;
        $data['number'] = $number;
        $data['user_id'] = $user_id;
        $data['pay_type'] = $pay_type;
        $data['add_type'] = $add_type;
        $data['password'] = $password;
        $data['e_blog_id'] = $e_blog_id;
        $data['s_blog_id'] = $s_blog_id;
        //1转入,2转出,3兑换
        if($data['add_type'] == 1){
            if (!$data['e_blog_id']) {
                return Response::jsonError("收款账号id为空");
            }
            if (!$data['money']) {
                return Response::jsonError("金额不能为空");
            }
//            if(isset($data['pay_type']) && $data['pay_type'] ==1){
//                return Response::jsonError("暂未开通微信储蓄,请使用支付宝充值!");
//            }
        }else if ($data['add_type'] == 2){
            if (!$data['s_blog_id']) {
                return Response::jsonError("提款账号id为空");
            }
            if (!$data['money']) {
                return Response::jsonError("金额不能为空");
            }
        }else if ($data['add_type'] == 3){
            if (!$data['e_blog_id']) {
                return Response::jsonError("收款账号id为空");
            }
            if (!$data['s_blog_id']) {
                return Response::jsonError("兑换账号id为空");
            }
            if (!$data['number'] &&  $data['number'] <1 ) {
                return Response::jsonError("数量不能为空");
            }
            if($data['s_blog_id'] ==1 && $data['e_blog_id'] == 2 && $data['number'] >5){
                return Response::jsonError("龙币每次最多兑换5枚");
            }
        }
        if (!$data['user_id']) {
            return Response::jsonError("用户ID为空");
        }
//        if (!$data['pay_type']) {
//            return Response::jsonError("支付类型为空");
//        }
        if (!$data['add_type']) {
            return Response::jsonError("操作类型为空");
        }
        if($data['add_type'] != 1) {
            if (!$data['password']) {
                return Response::jsonError("请输入支付密码");
            }
        }
        $lit = (new Order())->add($data);
        if($data['add_type'] ==1){
            if(is_array($lit)){
                return Response::jsonSuccessData($lit);
            }
        }
        if ($lit === true) {
            return Response::jsonSuccess("操作成功!");
        }
        return Response::jsonError($lit);
    }
    
    public function getBlogList(){
       return  $paginateData =   DB::table("blog")->select("id","title as text")->get();
    }


    /***
     * 龙币统计图
     */
    public function getLongList()
    {
        $numb = 0;
        $list = [];
        $j = 0;
        for ($i = 30; $i >= 0; $i--) {
            $j++;
            $currentDate = Carbon::now();
            $thirtyDaysAgo = $currentDate->subDays($i)->toDateString();
            $lit = SilverDollarCoin::where(["date_time" => $thirtyDaysAgo])->orderBy("date_time", "desc")->first();
            if (!$lit) {
                $list[$j]['price'] = $numb;
                $list[$j]['datetime'] = date("m/d",strtotime($thirtyDaysAgo));
                continue;
            }
            $numb = $lit->price;
            $list[$j]['price'] = $numb;
            $list[$j]['datetime'] = date("m/d",strtotime($thirtyDaysAgo));
        }
        return Response::jsonSuccessData(array_values($list));
    }

    public function getSilverDollarCoin()
    {
        $input = InputPackage::buildFromInput();
        $id = $input->getInteger('id');
        $data = [];
        $data['id'] = $id;
        if (!$data['id']) {
            return Response::jsonError("龙币ID不能为空");
        }

        $detail = (new Goldcoins())->getDetail($data);
        if(is_array($detail)){
            return Response::jsonSuccessData($detail);
        }
        return Response::jsonError($detail);
    }

    public function sendMessage()
    {
        $input = InputPackage::buildFromInput();
        $id = $input->getInteger('phone');
        $data = [];
        $data['phone'] = $id;
        if (!$data['phone']) {
            return Response::jsonError("电话号不能为空");
        }
        $is_phone =  self::isPhoneNumber($data['phone']);
        if(!$is_phone){
            return Response::jsonError("电话号格式不正确");
        }
        $today = Carbon::today();
        //获取短信验证每日次数
        $nums =  (new SmsLogs())->where(['phone'=>$data['phone']])->whereDate('created_at', '=', $today)->count();
        if($nums>10){
            return Response::jsonError("短信条数受限,请明日再发");
        };
        $lit['phone_num'] = $data['phone'];
        $lit['code'] = rand(000000,999999);
        $result = (new SendMess())::main($lit);
        if($result == 200){
            return Response::jsonSuccess("发送成功!");
        }
        return Response::jsonError("发送失败");

    }


    public static function isPhoneNumber($number) {
        $pattern = '/^1[3456789]\d{9}$/';
        return preg_match($pattern, $number);
    }


    /***
     * @return mixed
     * 获取h5页面介绍图
     */
    public function getIntroImg()
    {
       $result =  (new Config())->getIntroImage();

       if(!empty($result['value'])){
           if(substr($result['value'],0,4) != 'http'){
               $data['introimage'] = getenv("host_url").$result['value'];
           }else{
               $data['introimage'] = $result['value'];
           }
           return Response::jsonSuccessData($data);
       }
        return Response::jsonSuccessData([]);
    }


    /**
     * 获取购买的龙币列表
     */
    public function getOrderDragonList()
    {
        $input = InputPackage::buildFromInput();
        $user_id = $input->getInteger('user_id');
        $data = [];
        $data['user_id'] = $user_id;
        if (!$data['user_id']) {
            return Response::jsonError("用户ID不能为空");
        }
        $res = Order::getOrderDragonList($data);
        if($res){
            return Response::jsonSuccessData($res);
        }
        return Response::jsonError($res);
    }


















}